package com.yunxi.service.dubboService.impl.dealer;

import com.aiways.center.channel.api.IChannelApi;
import com.aiways.center.channel.api.IChannelPersonalApi;
import com.aiways.center.channel.api.dto.ChannelBaseDto;
import com.aiways.center.channel.api.dto.request.*;
import com.aiways.center.channel.api.dto.response.ChannelInvoiceRespDto;
import com.aiways.center.channel.api.dto.response.ChannelRespDto;
import com.aiways.center.channel.api.dto.response.ChannelStorageRespDto;
import com.aiways.center.channel.api.dto.response.ChannelTwonetsRespDto;
import com.aiways.center.channel.api.query.IChannelQueryApi;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dtyunxi.rest.RestResponse;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yunxi.account.pojo.AccountTypeVO;
import com.yunxi.baseDataToHub.pojo.iam.PmsOrganizeVO;
import com.yunxi.baseDataToHub.pojo.iam.PmsUserVO;
import com.yunxi.baseDataToHub.pojo.sap.BankVO;
import com.yunxi.baseDataToHub.pojo.sap.PartnerImgVO;
import com.yunxi.baseDataToHub.pojo.sap.PartnerInfoVO;
import com.yunxi.baseDataToHub.service.iam.IamDubboService;
import com.yunxi.baseDataToHub.service.sap.SapDubboService;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.util.GUIDGenerator;
import com.yunxi.core.util.WgrDate;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.dealer.pojo.*;
import com.yunxi.dealer.service.PartnerDubboService;
import com.yunxi.model.dealer.*;
import com.yunxi.sat.pojo.SatConfigVO;
import com.yunxi.sat.service.SatConfigDubboService;
import com.yunxi.service.localService.account.AccountTypeService;
import com.yunxi.service.localService.dealer.*;
import com.yunxi.service.localService.sys.AttachService;
import com.yunxi.sto.pojo.StoManageAddVO;
import com.yunxi.sto.service.StoManageDubboService;
import com.yunxi.sys.pojo.AttachVO;
import com.yunxi.sys.pojo.RoleUserVO;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.pojo.UserVO;
import com.yunxi.sys.service.RoleUserDubboService;
import com.yunxi.sys.service.StaffDubboService;
import com.yunxi.sys.service.UserDubboService;
import com.yunxi.util.RedisCacheService;
import com.yunxi.util.S2SEnums;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 渠道商信息 服务实现类
 * </p>
 *
 * @author
 * @since 2019-05-13
 */
public class PartnerDubboServiceImpl implements PartnerDubboService {

   @Autowired
   @Qualifier(value = "partnerServiceImpl")
   PartnerService partnerService;

   @Autowired
   @Qualifier(value = "partnerInvoiceServiceImpl")
   PartnerInvoiceService partnerInvoiceService;

   @Autowired
   @Qualifier(value = "partnerStorageServiceImpl")
   PartnerStorageService partnerStorageService;

   @Autowired
   @Qualifier(value = "partnerAccountServiceImpl")
   PartnerAccountService partnerAccountService;

   @Autowired
   @Qualifier(value = "partnerTwonetsServiceImpl")
   PartnerTwonetsService partnerTwonetsService;

   @Autowired
   @Qualifier(value = "partnerTypeServiceImpl")
   PartnerTypeService partnerTypeService;

   @Autowired
   @Qualifier(value = "accountTypeServiceImpl")
   AccountTypeService accountTypeService;

   @Autowired
   @Qualifier(value = "attachServiceImpl")
   AttachService sysAttachService;

   @Autowired
   IChannelApi channelApi;

   @Autowired
   IChannelPersonalApi channelPersonalApi;

   @Autowired
   IChannelQueryApi channelQueryApi;

   @Autowired
   SapDubboService sapDubboServiceImpl;

   @Autowired
   IamDubboService iamDubboServiceImpl;

   @Autowired
   StoManageDubboService stoManageDubboServiceImpl;

   @Autowired
   UserDubboService userDubboServiceImpl;

   @Autowired
   StaffDubboService staffDubboServiceImpl;

   @Autowired
   RoleUserDubboService roleUserDubboServiceImpl;

   @Autowired
   SatConfigDubboService satConfigDubboServiceImpl;

   @Autowired
   RedisCacheService rcs;

   @Value("${center.switch}")
   private String is2center;

   @Value("${sap.switch}")
   private String is2sap;

   @Value("${iam.switch}")
   private String is2IAM;

   private static final Logger logger = LoggerFactory.getLogger(PartnerDubboServiceImpl.class);

   @Override
   public List listByVo(PartnerVO v) {
      //排除售后渠道商
      v.setTenantId("pms");
      return partnerService.listByVo(v);
   }

   @Override
   public PartnerVO getById(String id) throws InvocationTargetException, IllegalAccessException {
      Partner partner = partnerService.getById(id);
      PartnerVO partnerVO = new PartnerVO();
      BeanUtils.copyProperties(partner, partnerVO);
      return partnerVO;
   }

   @Override
   public PageInfo<PartnerVO> findPageByVO2(PartnerVO partnerVO, Integer pageNum, Integer pageSize) {

      RestResponse restResponse = channelQueryApi.queryPage(BeanTools.bean2map(partnerVO));

      PageInfo<ChannelRespDto> data = (PageInfo<ChannelRespDto>) restResponse.getData();

      PageInfo<PartnerVO> partnerVOPageInfo = new PageInfo<>();

      partnerVOPageInfo.setPageNum(data.getPageNum());
      partnerVOPageInfo.setPageSize(data.getPageSize());
      partnerVOPageInfo.setSize(data.getSize());

      partnerVOPageInfo.setStartRow(data.getStartRow());
      partnerVOPageInfo.setEndRow(data.getEndRow());
      partnerVOPageInfo.setPages(data.getPages());
      partnerVOPageInfo.setPrePage(data.getPrePage());
      partnerVOPageInfo.setNextPage(data.getNextPage());

      partnerVOPageInfo.setIsFirstPage(data.isIsFirstPage());
      partnerVOPageInfo.setIsLastPage(data.isIsLastPage());
      partnerVOPageInfo.setHasPreviousPage(data.isHasPreviousPage());
      partnerVOPageInfo.setHasNextPage(data.isHasNextPage());
      partnerVOPageInfo.setNavigatepageNums(data.getNavigatepageNums());
      partnerVOPageInfo.setNavigateFirstPage(data.getNavigateFirstPage());
      partnerVOPageInfo.setNavigateLastPage(data.getNavigateLastPage());
      partnerVOPageInfo.setTotal(data.getTotal());
      List<ChannelRespDto> list = data.getList();

      List<PartnerVO> partnerVOList = partnerVOPageInfo.getList();
      ArrayList<PartnerInvoiceVO> partnerInvoiceVOS = new ArrayList<>();
      ArrayList<PartnerTwonetsVO> partnerTwonetsVOS = new ArrayList<>();
      for (ChannelRespDto channelRespDto : list) {
         PartnerVO partnerVO1 = new PartnerVO();
         partnerVO1.setPartnerId(channelRespDto.getId() + "");//渠道id
         partnerVO1.setPartnerCode(channelRespDto.getChannelCode());//渠道code
         partnerVO1.setPartnerSimpleName(channelRespDto.getChannelShortName());//渠道简称
         partnerVO1.setPartnerName(channelRespDto.getChannelName());//渠道名称
         partnerVO1.setParentCompanyCode(channelRespDto.getSalesOrganize());//归属销售组织
         partnerVO1.setProductAuthCode(channelRespDto.getProductAuthCode());//产品批售授权
         partnerVO1.setCountry(channelRespDto.getNation());//国家
         partnerVO1.setProvince(channelRespDto.getProvince());//省
         partnerVO1.setCity(channelRespDto.getCity());//市
         partnerVO1.setRegion(channelRespDto.getCounty());//区
         partnerVO1.setAddr(channelRespDto.getAddress());//渠道商地址
         //partnerVO1.setPostalCode();//邮政编码
         partnerVO1.setLegalPerson(channelRespDto.getLegalPerson());//法人代表
         partnerVO1.setLinkMan(channelRespDto.getLinkName());//联系人
         partnerVO1.setLinkPhone(channelRespDto.getLinkPhone());//联系电话
         partnerVO1.setMobilePhone(channelRespDto.getLinkPhone());//手机
         partnerVO1.setPartnerLevel(channelRespDto.getChannelLevel());//渠道商级别
         partnerVO1.setUnionCreditCode(channelRespDto.getCreditCode());//统一信用代码
         partnerVO1.setEntwepriseMailbox(channelRespDto.getEmail());//销售企业邮箱
         partnerVO1.setFax(channelRespDto.getFax());//传真
         partnerVO1.setCheckPerson(channelRespDto.getCheckPerson());//验收人
         partnerVO1.setCheckTime(channelRespDto.getCheckTime());//验收完成时间
         partnerVO1.setIsAfhalen(channelRespDto.getIsSelfTake());//是否自提
         partnerVO1.setGpsX(channelRespDto.getGpsX());//坐标x
         partnerVO1.setGpsY(channelRespDto.getGpsY());//坐标y
         partnerVO1.setStatus(channelRespDto.getStatus());//状态 1入网 2退网 3冻结
         partnerVOList.add(partnerVO1);

         List<ChannelInvoiceRespDto> channelInvoiceReqDtos = channelRespDto.getChannelInvoiceReqDtos();

         for (ChannelInvoiceRespDto channelInvoiceReqDto : channelInvoiceReqDtos) {
            PartnerInvoiceVO partnerInvoiceVO = new PartnerInvoiceVO();
            partnerInvoiceVO.setPartnerCode(channelInvoiceReqDto.getChannelCode());//渠道代码
            // partnerInvoiceVO.setBankCode(channelInvoiceReqDto.get);//银行国家代码
            //银行编号
            partnerInvoiceVO.setBankAccount(channelInvoiceReqDto.getBankAccount());//开户帐号
            //partnerInvoiceVO.setBankHolder();//帐户持有人姓名
            partnerInvoiceVO.setInvoiceCode(channelInvoiceReqDto.getInvoiceCode());//发票代码
            partnerInvoiceVO.setBank(channelInvoiceReqDto.getBankName());//开户银行名称
            //partnerInvoiceVO.setBankEmail();//银行邮箱
            //银行地址
            partnerInvoiceVO.setStatus(channelInvoiceReqDto.getStatus());//状态

            partnerInvoiceVOS.add(partnerInvoiceVO);
         }
         List<ChannelTwonetsRespDto> channelTwonetsRespDtos = channelRespDto.getChannelTwonetsRespDtos();
         for (ChannelTwonetsRespDto channelTwonetsRespDto : channelTwonetsRespDtos) {
            PartnerTwonetsVO partnerTwonetsVO = new PartnerTwonetsVO();
            partnerTwonetsVO.setPartnerCode(channelTwonetsRespDto.getChannelCode());//渠道商代码
            partnerTwonetsVO.setTwoCode(channelTwonetsRespDto.getTwonetsCode());//二网代码
            partnerTwonetsVO.setTwoName(channelTwonetsRespDto.getTwonetsName());//二网名称
            partnerTwonetsVO.setTwoSimpleName(channelTwonetsRespDto.getTwonetsShortName());//二网简称
            partnerTwonetsVO.setTwoAddr(channelTwonetsRespDto.getTwonetsAddr());//二网地址
            partnerTwonetsVO.setStatus(channelTwonetsRespDto.getStatus());//二网状态
            partnerTwonetsVOS.add(partnerTwonetsVO);
         }
         List<ChannelStorageRespDto> channelStorageReqDtos = channelRespDto.getChannelStorageReqDtos();
         for (ChannelStorageRespDto channelStorageReqDto : channelStorageReqDtos) {
            PartnerStorageVO partnerStorageVO = new PartnerStorageVO();
            partnerStorageVO.setPartnerCode(channelStorageReqDto.getChannelCode());//渠道代码
            partnerStorageVO.setStorageCode(channelStorageReqDto.getStorageCode());//仓库代码
            partnerStorageVO.setStorageName(channelStorageReqDto.getStorageName());//仓库名称
            partnerStorageVO.setLinkMan(channelStorageReqDto.getLinkMan());//联系人
            partnerStorageVO.setLinkPhone(channelStorageReqDto.getLinkPhone());//联系电话
            partnerStorageVO.setStatus(channelStorageReqDto.getStatus());//状态

            partnerStorageVO.setAddr(channelStorageReqDto.getAddress());//仓库地址
            partnerStorageVO.setGpsBaiduX(channelStorageReqDto.getGpsX());//坐标x
            partnerStorageVO.setGpsBaiduY(channelStorageReqDto.getGpsY());//坐标Y
         }


         //partnerVO1.setPartnerInvoiceVOList();


      }
      return partnerVOPageInfo;
   }

   @Override
   @Transactional
   public ApiResult updateBatch(List<PartnerStatusVO> ids, LoginInfo loginInfo) throws Exception {
      for (PartnerStatusVO statusVO : ids) {

         QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("PARTNER_ID", statusVO.getPartnerId());
         Partner one = partnerService.getOne(queryWrapper);
         one.setUpdateBy(loginInfo.getUserCode());
         one.setStatus(statusVO.getStatus());

         PartnerVO partnerVO = new PartnerVO();
         BeanUtils.copyProperties(one, partnerVO);

         //将渠道状态更改信息传入中台
         if ("true".equals(is2center)) {
            ApiResult result = pms2CenterUpdateStatus(partnerVO);
            if (result!=null) return result;
         }
         //将渠道状态更改信息传入SAP
         if (partnerVO.getStatus().equals(1)) {//入网
            if ("true".equals(is2sap)) {
               ApiResult result = pms2SAP2(partnerVO, S2SEnums.OperatorType.update.getKey());
               if (result!=null) return result;
            }
            ApiResult result = updateUserStatus(partnerVO, 1, 0, loginInfo);//启用 非游客
            if (result!=null) return result;
         }
         if (partnerVO.getStatus().equals(2)) {//退网
            if ("true".equals(is2sap)) {
               ApiResult result = pms2SAP2(partnerVO, S2SEnums.OperatorType.delete.getKey());
               if (result!=null) return result;
            }
            ApiResult result = updateUserStatus(partnerVO, 0, 1, loginInfo);//禁用 游客
            if (result!=null) return result;
         }
         if (partnerVO.getStatus().equals(3)) {//冻结
            if ("true".equals(is2sap)) {
               ApiResult result = pms2SAP2(partnerVO, S2SEnums.OperatorType.blocking.getKey());
               if (result!=null) return result;
            }
            ApiResult result = updateUserStatus(partnerVO, 1, 1, loginInfo);//启用 游客
            if (result!=null) return result;
         }
         Partner p = new Partner();
         p.setUpdateBy(loginInfo.getUserCode());
         p.setStatus(statusVO.getStatus());
         partnerService.update(p, queryWrapper);
      }
      return ResponseUtil.ok();
   }

   @Override
   public PageInfo pageSel(PartnerVO v, Integer pageNum, Integer pageSize) {
      return partnerService.pageSel(v, pageNum, pageSize);
   }

   @Override
   public ApiResult updateBatchArea(List<PartnerAreaVO> partnerAreaVOList, LoginInfo loginInfo) {
      for (PartnerAreaVO partnerAreaVO : partnerAreaVOList) {
         QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("PARTNER_ID", partnerAreaVO.getPartnerId());

         Partner partner = new Partner();
         BeanUtils.copyProperties(partnerAreaVO, partner);
         partner.setUpdateBy(loginInfo.getUserCode());
         partnerService.update(partner, queryWrapper);
      }
      return ResponseUtil.ok();
   }

   @Override
   public ApiResult listByAreaCode(PartnerVO partnerVO, Integer pageNum, Integer pageSize) {

      //筛选产品授权
      String vehicleCodeListStr = partnerVO.getVehicleCodeListStr();
      if(StringUtil.isNotEmpty(vehicleCodeListStr)){
         String[] split = vehicleCodeListStr.split(",");
         List<String> vc = Arrays.asList(split);
         partnerVO.setVehicleCodeList(vc);
      }
      List<String> vehicleCodeList = partnerVO.getVehicleCodeList();
      if (vehicleCodeList!=null && vehicleCodeList.size()>0){
         //集合去重
         vehicleCodeList = vehicleCodeList.stream().distinct().collect(Collectors.toList());
      }

      if(StringUtils.isNotEmpty(partnerVO.getBusinessCodeIn())){
         String[] codes = partnerVO.getBusinessCodeIn().split(",");
         String calc = "";
         for(int i=0;i<codes.length;i++){
            calc+= "'"+codes[i]+"'";
            if(i!=codes.length-1){
               calc+= ",";
            }
         }
         partnerVO.setBusinessCodeIn(calc);
      }

      return partnerService.listByAreaCode(partnerVO, pageNum, pageSize);
   }

   @Override
   public List<PartnerVO> listByAreaCodes(List<PartnerVO> partnerVOList) {

      ArrayList<PartnerVO> partnerVOS = new ArrayList<>();
      if (partnerVOList != null && partnerVOList.size() > 0) {
         for (PartnerVO vo : partnerVOList) {
            List<PartnerVO> list = partnerService.listByAreaCodes(vo);
            for (PartnerVO partnerVO : list) {
               partnerVOS.add(partnerVO);
            }
         }
      }
      return partnerVOS;
   }

   @Override
   public String leastPartner(String clueType, String province,String vehicleCode,String city) {

      return partnerService.leastPartner(clueType, province,vehicleCode,city);
   }

   @Override
   public List<PartnerVO> listByProductAuth(String partnerCode, String productTypeCode) {
      return partnerService.listByProductAuth(partnerCode,productTypeCode);
   }

   @Override
   @Transactional
   public ApiResult saveOrUpdate(PartnerVO partnerVO, LoginInfo loginInfo) throws Exception {
      //渠道主信息
      if (StringUtils.isEmpty(partnerVO.getTenantId())) return ResponseUtil.fail(-1, "请指定渠道商类型");
      if ("pms".equals(partnerVO.getTenantId()) && StringUtils.isEmpty(partnerVO.getBusinessCode())) return ResponseUtil.fail(-1, "请指定渠道商业务类型"+partnerVO.getPartnerCode()+"_"+partnerVO.getTenantId());
      if (StringUtils.isEmpty(partnerVO.getPartnerCode())) return ResponseUtil.fail(502, "渠道商代码或名称为空");
      if ("010".equals(partnerVO.getBusinessCode())){
         if (!"B01".equals(partnerVO.getAccountGroupCode()) && !"F01".equals(partnerVO.getAccountGroupCode())){
            return ResponseUtil.fail(-1,"金融业务,请选择金融伙伴或银行机构");
         }
      }else {
         if ("B01".equals(partnerVO.getAccountGroupCode()) || "F01".equals(partnerVO.getAccountGroupCode())){
            return ResponseUtil.fail(-1,"非金融业务类型,不可选择金融伙伴或银行机构");
         }
      }
      boolean isFirst = false;
      if (StringUtils.isEmpty(partnerVO.getPartnerId())) {
         isFirst = true;
      }
      ApiResult apiResult = null;
      //渠道基本信息
      apiResult = addOrUpdatePartner(partnerVO, loginInfo, isFirst);
      if (apiResult != null) return apiResult;

      //渠道二网
      apiResult = addOrUpdatePartnerTwonets(partnerVO, loginInfo);
      if (apiResult != null) return apiResult;

      //渠道发运信息
      List<PartnerStorageVO> partnerStorageVOList = partnerVO.getPartnerStorageVOList();
      apiResult = addOrUpdatePartnerStorage(partnerVO, loginInfo, partnerStorageVOList);
      if (apiResult != null) return apiResult;

      //渠道发票
      List<PartnerInvoiceVO> partnerInvoiceVOList = partnerVO.getPartnerInvoiceVOList();
      apiResult = addOrUpdatePartnerInvoice(partnerVO, loginInfo, partnerInvoiceVOList);
      if (apiResult != null) return apiResult;

      //附件表
      if ("pms".equals(partnerVO.getTenantId())) {
         if (partnerVO.getAttachVOList() != null && partnerVO.getAttachVOList().size() > 0) {
            sysAttachService.saveByAttachVoList(partnerVO.getAttachVOList(), "pms_partner", partnerVO.getPartnerCode(), loginInfo);
         }else {
            sysAttachService.delByBusSubId("pms_partner",partnerVO.getPartnerCode());
         }
      }else {
         if (partnerVO.getAttachVOList() != null && partnerVO.getAttachVOList().size() > 0) {
            sysAttachService.saveByAttachVoList(partnerVO.getAttachVOList(), "ups_pms_partner", partnerVO.getPartnerCode(), loginInfo);
         }else {
            sysAttachService.delByBusSubId("ups_pms_partner",partnerVO.getPartnerCode());
         }
      }
      //图片
      if (partnerVO.getImageVOList() != null && partnerVO.getImageVOList().size() > 0) {
         sysAttachService.saveByAttachVoList(partnerVO.getImageVOList(), "pms_partner_img", partnerVO.getPartnerCode(), loginInfo);
      }else {
         sysAttachService.delByBusSubId("pms_partner_img",partnerVO.getPartnerCode());
      }
      //关系表
      addOrUpdatePartnerType(partnerVO, loginInfo);
      //渠道账户
      addOrUpdatePartnerAccount(partnerVO, loginInfo, partnerStorageVOList, partnerInvoiceVOList);
      //新增SAT配置
      addSatConfig(partnerVO, loginInfo, isFirst);
      //创建一个渠道商管理员用户
      if (isFirst) {
         return createAdminUser(partnerVO, loginInfo);
      }

      return ResponseUtil.ok("保存成功");
   }

   @Override
   @Transactional
   public ApiResult saveOrUpdateByVip(PartnerVO partnerVO, boolean isFirst,LoginInfo loginInfo) throws Exception {
      //渠道主信息
      if (StringUtils.isEmpty(partnerVO.getTenantId())) return ResponseUtil.fail(-1, "请指定渠道商类型");
      if ("pms".equals(partnerVO.getTenantId()) && StringUtils.isEmpty(partnerVO.getBusinessCode())) return ResponseUtil.fail(-1, "请指定渠道商业务类型"+partnerVO.getPartnerCode()+"_"+partnerVO.getTenantId());
      if (StringUtils.isEmpty(partnerVO.getPartnerCode())) return ResponseUtil.fail(502, "渠道商代码或名称为空");
      if ("010".equals(partnerVO.getBusinessCode())){
         if (!"B01".equals(partnerVO.getAccountGroupCode()) && !"F01".equals(partnerVO.getAccountGroupCode())){
            return ResponseUtil.fail(-1,"金融业务,请选择金融伙伴或银行机构");
         }
      }else {
         if ("B01".equals(partnerVO.getAccountGroupCode()) || "F01".equals(partnerVO.getAccountGroupCode())){
            return ResponseUtil.fail(-1,"非金融业务类型,不可选择金融伙伴或银行机构");
         }
      }
      ApiResult apiResult = null;
      //渠道基本信息
      apiResult = addOrUpdatePartner(partnerVO, loginInfo, isFirst);
      if (apiResult != null) return apiResult;

      //渠道二网
      apiResult = addOrUpdatePartnerTwonets(partnerVO, loginInfo);
      if (apiResult != null) return apiResult;

      //渠道发运信息
      List<PartnerStorageVO> partnerStorageVOList = partnerVO.getPartnerStorageVOList();
      apiResult = addOrUpdatePartnerStorage(partnerVO, loginInfo, partnerStorageVOList);
      if (apiResult != null) return apiResult;

      //渠道发票
      List<PartnerInvoiceVO> partnerInvoiceVOList = partnerVO.getPartnerInvoiceVOList();
      apiResult = addOrUpdatePartnerInvoice(partnerVO, loginInfo, partnerInvoiceVOList);
      if (apiResult != null) return apiResult;

      //关系表
      addOrUpdatePartnerType(partnerVO, loginInfo);
      //渠道账户
      addOrUpdatePartnerAccount(partnerVO, loginInfo, partnerStorageVOList, partnerInvoiceVOList);

      //创建一个渠道商管理员用户
      if (isFirst) {
         return createAdminUser(partnerVO, loginInfo);
      }

      return ResponseUtil.ok("保存成功");
   }

   @Override
   public PartnerVO getByPartnerCode(String partnerCode) {
      return partnerService.getByPartnerCode(partnerCode);
   }

    @Override
    public ApiResult exportPartner(PartnerVO partnerVO) {
      if (StringUtils.isEmpty(partnerVO.getTenantId())) return ResponseUtil.fail(-1,"请选择渠道类型");
      if ("pms".equals(partnerVO.getTenantId())){
         List<ExportPartnerVO> list = partnerService.exportPartnerPMS(partnerVO);
         return ResponseUtil.ok(list);
      }else if ("ups".equals(partnerVO.getTenantId())){
         List<ExportPartnerVOUps> list = partnerService.exportPartnerUPS(partnerVO);
         return ResponseUtil.ok(list);
      }
      return ResponseUtil.fail();
    }

    private void addSatConfig(PartnerVO partnerVO, LoginInfo loginInfo, boolean isFirst) throws Exception {
      if ("pms".equals(partnerVO.getTenantId())) {
         if (isFirst) {
            SatConfigVO satConfigVO = new SatConfigVO();
            satConfigVO.setPartnerCode(partnerVO.getPartnerCode());
            satConfigVO.setSetName("配置名称" + partnerVO.getPartnerCode());
            satConfigVO.setDriveInfo("本人在试乘试驾过程中，将严格遵守国家及地方有关行车驾驶及乘车的一切法律和法规要求，并服从该特约销售服务店提出的一切指示，做到安全、文明驾驶，已尽最大努力和善意确保试乘试驾车辆的安全和完好。否则，对试驾过程中造成对自身或他人的人身伤亡、特约销售服务店或他人财产的一切损失，本人将承担一切责任。");
            satConfigVO.setDriveAttention("注意事项");
            satConfigVO.setCreateBy(loginInfo.getUserCode());
            satConfigDubboServiceImpl.saveOrUpdate(satConfigVO);
         }
      }
   }

   private void addOrUpdatePartnerAccount(PartnerVO partnerVO, LoginInfo loginInfo, List<PartnerStorageVO> partnerStorageVOList, List<PartnerInvoiceVO> partnerInvoiceVOList) throws IllegalAccessException {
      List<PartnerAccountVO> partnerAccountVOList = partnerVO.getPartnerAccountVOList();
      if ("pms".equals(partnerVO.getTenantId())) {
         if (partnerAccountVOList == null || partnerAccountVOList.size() <= 0) {
            if (!StringUtils.isEmpty(partnerVO.getPartnerCode()) &&
                    !StringUtils.isEmpty(partnerVO.getPartnerName()) &&
                    partnerStorageVOList != null && partnerStorageVOList.size() > 0 &&
                    partnerInvoiceVOList != null && partnerInvoiceVOList.size() > 0 &&
                    !BeanTools.isAllFieldNull(partnerStorageVOList.get(0)) && !BeanTools.isAllFieldNull(partnerInvoiceVOList.get(0))) {
               //新增账户
               List list = accountTypeService.listByVo(new AccountTypeVO());
               for (int i = 0; i < list.size(); i++) {
                  AccountTypeVO accountTypeVO = (AccountTypeVO) list.get(i);

                  PartnerAccount partnerAccount = new PartnerAccount();
                  if (accountTypeVO.getAccountTypeCode().equals("D")) {//返利账户
                     partnerAccount.setIsRebate("Y");
                  }
                  partnerAccount.setCreateBy(loginInfo.getUserCode());
                  partnerAccount.setIsRebate("N");
                  partnerAccount.setPartnerCode(partnerVO.getPartnerCode());
                  partnerAccount.setStatus(partnerVO.getStatus());
                  partnerAccount.setAccountId(UUID.randomUUID().toString().replaceAll("-", ""));
                  //渠道商账户code = 渠道商code + 账户类型code
                  partnerAccount.setAccountCode(partnerVO.getPartnerCode() + "_" + accountTypeVO.getAccountTypeCode());
                  //渠道商账户名称 = 渠道商名称 + 账户类型名称
                  partnerAccount.setAccountName(partnerVO.getPartnerName() + "_" + accountTypeVO.getAccountTypeName());
                  partnerAccount.setAccountTypeCode(accountTypeVO.getAccountTypeCode());
                  partnerAccount.setAccountAmount(new BigDecimal(0.00));
                  partnerAccount.setAccountBalance(new BigDecimal(0.00));
                  partnerAccountService.saveOrUpdate(partnerAccount);
               }
            }
         }
      }
   }

   private void addOrUpdatePartnerType(PartnerVO partnerVO, LoginInfo loginInfo) {
      if ("pms".equals(partnerVO.getTenantId())) {
         List<PartnerTypeVO> partnerTypeVOList = partnerVO.getPartnerTypeVOList();
         List<String> accountPropCodeList = partnerVO.getAccountPropCodeList();
         if (accountPropCodeList != null && accountPropCodeList.size() > 0 &&
                 !StringUtils.isEmpty(partnerVO.getBusinessCode()) && !StringUtils.isEmpty(partnerVO.getAccountGroupCode())) {
            for (String accountPropCode : accountPropCodeList) {
               PartnerType partnerType = new PartnerType();
               partnerType.setCreateBy(loginInfo.getUserCode());
               partnerType.setAuthId(UUID.randomUUID().toString().replaceAll("-", ""));
               partnerType.setPartnerCode(partnerVO.getPartnerCode());
               partnerType.setBusinessCode(partnerVO.getBusinessCode());
               partnerType.setAccountGroupCode(partnerVO.getAccountGroupCode());
               partnerType.setAccountPropCode(accountPropCode);
               partnerTypeService.saveOrUpdate(partnerType);
            }
         }

         if (partnerTypeVOList != null) {
            List<PartnerType> partnerTypes = BeanTools.copyListToList(partnerTypeVOList, PartnerType.class);
            for (PartnerType partnerType : partnerTypes) {
               partnerTypeService.removeById(partnerType.getAuthId());
            }
         }
      }
   }

   private ApiResult addOrUpdatePartnerInvoice(PartnerVO partnerVO, LoginInfo loginInfo, List<PartnerInvoiceVO> partnerInvoiceVOList) {
      if (partnerInvoiceVOList != null && partnerInvoiceVOList.size() > 0) {
         List<PartnerInvoice> partnerInvoices = BeanTools.copyListToList(partnerInvoiceVOList, PartnerInvoice.class);
         for (PartnerInvoice partnerInvoice : partnerInvoices) {
            if (!StringUtils.isEmpty(partnerInvoice.getBankCode())) {
               partnerInvoice.setPartnerCode(partnerVO.getPartnerCode());
               partnerInvoice.setStatus(partnerVO.getStatus());
               if (StringUtils.isEmpty(partnerInvoice.getInvoiceId())) {
                  partnerInvoice.setCreateBy(loginInfo.getUserCode());
                  partnerInvoice.setInvoiceId(UUID.randomUUID().toString().replaceAll("-", ""));
                  partnerInvoice.setInvoiceCode(partnerVO.getPartnerCode() + "_" + partnerInvoice.getBankAccount());
                  //将渠道发票信息传入中台
                  if ("true".equals(is2center)) {
                     ChannelInvoiceReqDto channelInvoiceReqDto = new ChannelInvoiceReqDto();
                     setCenterInvoice(partnerVO, partnerInvoice, channelInvoiceReqDto);
                     if (pms2CenterInvoicesAdd(channelInvoiceReqDto)) return ResponseUtil.fail(-1, "--中台发票添加报错");
                  }
               } else {
                  partnerInvoice.setUpdateBy(loginInfo.getUserCode());
                  //将渠道发票信息传入中台
                  if ("true".equals(is2center)) {
                     ChannelInvoiceReqDto channelInvoiceReqDto = new ChannelInvoiceReqDto();
                     setCenterInvoice(partnerVO, partnerInvoice, channelInvoiceReqDto);
                     if (pms2CenterInvoicesUpdate(channelInvoiceReqDto)) return ResponseUtil.fail(-1, "--中台发票更新报错");
                  }
               }
               partnerInvoiceService.saveOrUpdate(partnerInvoice);
            }
         }
      }
      return null;
   }

   private ApiResult addOrUpdatePartnerStorage(PartnerVO partnerVO, LoginInfo loginInfo, List<PartnerStorageVO> partnerStorageVOList) throws Exception {
      if ("pms".equals(partnerVO.getTenantId())) {
         if (partnerStorageVOList != null && partnerStorageVOList.size() > 0) {
            List<PartnerStorage> partnerStorages = BeanTools.copyListToList(partnerStorageVOList, PartnerStorage.class);
            for (PartnerStorage partnerStorage : partnerStorages) {
               if (!StringUtils.isEmpty(partnerStorage.getAddr())) {
                  partnerStorage.setPartnerCode(partnerVO.getPartnerCode());
                  partnerStorage.setStatus(partnerVO.getStatus());
                  partnerStorage.setStorageName(partnerVO.getPartnerCode() + "仓库");
                  if (StringUtils.isEmpty(partnerStorage.getStorageId())) {
                     partnerStorage.setCreateBy(loginInfo.getUserCode());
                     StoManageAddVO stoManageAddVO = new StoManageAddVO();
                     stoManageAddVO.setStorageName(partnerStorage.getStorageName() + GUIDGenerator.getPrimaryKey());
                     stoManageAddVO.setStorageLocation(partnerStorage.getAddr());
                     String storageCode = stoManageDubboServiceImpl.partnerStorage(stoManageAddVO);

                     partnerStorage.setStorageCode(storageCode);
                     partnerStorage.setStorageId(UUID.randomUUID().toString().replaceAll("-", ""));
                     //将渠道发运信息传入中台
                     if ("true".equals(is2center)) {
                        ChannelStorageReqDto channelStorageReqDto = new ChannelStorageReqDto();
                        setCenterStorage(partnerVO, partnerStorage, channelStorageReqDto);
                        ApiResult result = pms2CenterStorangeAdd(channelStorageReqDto);
                        if (result!=null) return result;
                     }
                  } else {
                     partnerStorage.setUpdateBy(loginInfo.getUserCode());
                     //将渠道发运信息传入中台
                     if ("true".equals(is2center)) {
                        ChannelStorageReqDto channelStorageReqDto = new ChannelStorageReqDto();
                        setCenterStorage(partnerVO, partnerStorage, channelStorageReqDto);
                        ApiResult result = pms2CenterStorangeUpdate(channelStorageReqDto);
                        if (result!=null) return result;
                     }
                  }
                  partnerStorageService.saveOrUpdate(partnerStorage);
               }
            }
         }
      }
      return null;
   }

   private ApiResult addOrUpdatePartnerTwonets(PartnerVO partnerVO, LoginInfo loginInfo) {
      if ("pms".equals(partnerVO.getTenantId())) {
         List<PartnerTwonetsVO> partnerTwonetsVOList = partnerVO.getPartnerTwonetsVOList();
         if (partnerTwonetsVOList != null && partnerTwonetsVOList.size() > 0) {
            List<PartnerTwonets> partnerTwonets = BeanTools.copyListToList(partnerTwonetsVOList, PartnerTwonets.class);
            for (PartnerTwonets partnerTwonet : partnerTwonets) {
               if (!StringUtils.isEmpty(partnerTwonet.getTwoCode())) {
                  partnerTwonet.setPartnerCode(partnerVO.getPartnerCode());
                  partnerTwonet.setStatus(partnerVO.getStatus());
                  //二网新增
                  if (StringUtils.isEmpty(partnerTwonet.getTwonetsId())) {
                     partnerTwonet.setTwonetsId(UUID.randomUUID().toString().replaceAll("-", ""));
                     partnerTwonet.setCreateBy(loginInfo.getUserCode());
                     //将渠道二网信息传入中台
                     if ("true".equals(is2center)) {
                        ChannelTwonetsReqDto channelTwonetsReqDto = new ChannelTwonetsReqDto();
                        setCenterTwonets(partnerVO, partnerTwonet, channelTwonetsReqDto);
                        ApiResult apiResult = pms2CenterTwonetsAdd(channelTwonetsReqDto);
                        if (apiResult!=null) return apiResult;
                     }

                     //将渠道二网 组织机构信息传入SAP
                     if ("true".equals(is2sap)) {
                        PartnerInfoVO partnerInfoVO = new PartnerInfoVO();
                        partnerInfoVO.setKunnr(partnerTwonet.getTwoCode());
                        partnerInfoVO.setName1(partnerTwonet.getTwoName());
                        partnerInfoVO.setSortl(partnerTwonet.getTwoSimpleName());
                        partnerInfoVO.setStras(partnerTwonet.getTwoAddr());
                        ApiResult apiResult = pms2SAP2(partnerVO, partnerInfoVO, S2SEnums.OperatorType.insert.getKey());
                        if (apiResult!=null) return apiResult;
                     }
                  } else {
                     partnerTwonet.setUpdateBy(loginInfo.getUserCode());
                     //二网修改
                     //将渠道二网信息传入中台
                     if ("true".equals(is2center)) {
                        ChannelTwonetsReqDto channelTwonetsReqDto = new ChannelTwonetsReqDto();
                        setCenterTwonets(partnerVO, partnerTwonet, channelTwonetsReqDto);
                        ApiResult apiResult = pms2CenterTwonetsUpdate(channelTwonetsReqDto);
                        if (apiResult!=null) return apiResult;
                     }
                     //将渠道二网 组织机构信息传入SAP
                     if ("true".equals(is2sap)) {
                        PartnerInfoVO partnerInfoVO = new PartnerInfoVO();
                        partnerInfoVO.setKunnr(partnerTwonet.getTwoCode());
                        partnerInfoVO.setName1(partnerTwonet.getTwoName());
                        partnerInfoVO.setSortl(partnerTwonet.getTwoSimpleName());
                        partnerInfoVO.setStras(partnerTwonet.getTwoAddr());
                        ApiResult apiResult = pms2SAP2(partnerVO, partnerInfoVO, S2SEnums.OperatorType.update.getKey());
                        if (apiResult!=null) return apiResult;
                     }
                  }
                  partnerTwonetsService.saveOrUpdate(partnerTwonet);
               }
            }
         }
      }
      return null;
   }

   private ApiResult addOrUpdatePartner(PartnerVO partnerVO, LoginInfo loginInfo,  boolean isFirst) throws Exception {
      ChannelReqDto channelReqDto = new ChannelReqDto();
      if (isFirst) {
         partnerVO.setStatus(1);
         if ("pms".equals(partnerVO.getTenantId())) {
            partnerVO.setAkont("1122010000");//统驭科目
         }else {
            partnerVO.setProductAuthCodeJson(null);
         }
         partnerVO.setCreateBy(loginInfo.getUserCode());
         //将渠道信息传入中台
         if ("true".equals(is2center)) {
            setProp(partnerVO, channelReqDto);
            ApiResult apiResult = pms2CenterAdd(channelReqDto);
            if (apiResult != null) return apiResult;
         }
         //将渠道信息传入SAP +组织机构信息
         if ("true".equals(is2sap)) {
            ApiResult apiResult = pms2SAP(partnerVO, S2SEnums.OperatorType.insert.getKey());
            if (apiResult != null) return apiResult;
         }
      } else {
         partnerVO.setUpdateBy(loginInfo.getUserCode());
         if ("ups".equals(partnerVO.getTenantId())) {
            partnerVO.setProductAuthCodeJson(null);
         }
         //将渠道信息传入中台
         if ("true".equals(is2center)) {
            setProp(partnerVO, channelReqDto);
            ApiResult apiResult = pms2CenterUpdate(partnerVO, channelReqDto);
            if (apiResult != null) return apiResult;
         }
         //将渠道信息传入SAP +组织机构信息
         if ("true".equals(is2sap)) {
            ApiResult apiResult = pms2SAP(partnerVO, S2SEnums.OperatorType.update.getKey());
            if (apiResult != null) return apiResult;
         }
      }
      Partner partner = new Partner();
      BeanUtils.copyProperties(partnerVO, partner);

      partner.setManageAreaCode(null);
      if (isFirst){
         partnerService.saveOrUpdate(partner);
      }else {
         boolean b = partnerService.updateById(partner);
         if (!b) throw new Exception("操作冲突,请稍后重试");
      }
      return null;
   }

   private ApiResult createAdminUser(PartnerVO partnerVO, LoginInfo loginInfo) throws Exception {

      //创建一个管理员用户
      UserVO u = new UserVO();
      u.setCreateBy(loginInfo.getUserCode());
      u.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));

      u.setPassword("uWjRsy6BsLY=");
      u.setRealName("管理员");
      u.setUserType(3);
      u.setTenantId(partnerVO.getTenantId());
      // 并且用户角色表中创建数据设置默认角色
      RoleUserVO ru = new RoleUserVO();
      ru.setCreateBy(loginInfo.getUserCode());
      //如果是金融伙伴
      if ("F01".equals(partnerVO.getAccountGroupCode()) ){
         ru.setRoleId("roleFinance");
      }else if ("B01".equals(partnerVO.getAccountGroupCode())){
         ru.setRoleId("roleBank");
      }else {
         ru.setRoleId("rolePartnerAdmin");
      }
      ru.setUserId(u.getUserId());

      //创建一个人员数据 并且关联用户
      StaffVO staffVO = new StaffVO();
      staffVO.setCreateBy(loginInfo.getUserCode());
      staffVO.setPassword(u.getPassword());
      staffVO.setStaffName("管理员");
      staffVO.setOrgId(partnerVO.getPartnerCode());
      staffVO.setPartnerCode(partnerVO.getPartnerCode());
      staffVO.setStatus(1);
      staffVO.setTenantId(partnerVO.getTenantId());
      if ("pms".equals(partnerVO.getTenantId())) {
         staffVO.setMobilePhone(partnerVO.getMobilePhone());
         staffVO.setTenantId("pms");
         staffVO.setAccountNo("PMS_" + partnerVO.getPartnerCode() + "A");
         u.setUserCode("PMS_" + partnerVO.getPartnerCode() + "A");
      } else {
         staffVO.setMobilePhone(partnerVO.getPhone());
         staffVO.setTenantId("ups");
         staffVO.setAccountNo("UPS_" + partnerVO.getPartnerCode() + "A");
         u.setUserCode("UPS_" + partnerVO.getPartnerCode() + "A");
      }

      StaffVO staff = staffDubboServiceImpl.getByUser(u);
      if (staff!=null && StringUtils.isNotEmpty(staff.getStaffId())) {
         return ResponseUtil.fail(-1,"该人员账号已存在"+u.getUserCode()+",请更换渠道商编号");
      }
      UserVO userVO = userDubboServiceImpl.getByUserCode(u.getUserCode());
      if (userVO!=null && StringUtils.isNotEmpty(userVO.getUserId())){
         return ResponseUtil.fail(-1,"该用户账号已存在"+u.getUserCode()+",请更换渠道商编号");
      }


      //将渠道人员信息传入IAM
      if ("true".equals(is2IAM)) {
         if (pms2IAM(staffVO, S2SEnums.OperatorType.insert.getKey()))
            return ResponseUtil.fail(-1, "--将渠道人员信息传入IAM出错--");
      }

      //将渠道人员信息传入中台
      if ("true".equals(is2center)) {
         ChannelPersonalReqDto channelPersonalReqDto = setChannelPersonalReqDto(staffVO);
         ApiResult apiResult = pms2CenterChannelPersonalAdd(channelPersonalReqDto);
         if (apiResult!=null){ return apiResult; }
      }


      userDubboServiceImpl.save(u);
      roleUserDubboServiceImpl.save(ru);
      staffDubboServiceImpl.save(staffVO);

      return ResponseUtil.ok("保存成功 已创建新的渠道商");
   }

   private ChannelPersonalReqDto setChannelPersonalReqDto(StaffVO staffVO) {
      ChannelPersonalReqDto channelPersonalReqDto = new ChannelPersonalReqDto();
      channelPersonalReqDto.setChannelCode(staffVO.getPartnerCode());//渠道商代码
      channelPersonalReqDto.setAccount(staffVO.getAccountNo());//登录账号
      channelPersonalReqDto.setPassword(staffVO.getPassword());//密码
      channelPersonalReqDto.setRealName(staffVO.getStaffName());//姓名
      channelPersonalReqDto.setNickName("");//昵称
      channelPersonalReqDto.setPhone(staffVO.getMobilePhone());//联系电话
      channelPersonalReqDto.setEmail("");//邮箱
      channelPersonalReqDto.setLevel("Y");//是否管理员:Y/N
      channelPersonalReqDto.setOrganizationCode("none");//部门编码
      channelPersonalReqDto.setOrganizationName("没有");//部门名称
      channelPersonalReqDto.setPositionCode("ZW0802");//职位编码
      channelPersonalReqDto.setPositionName("销售经理");//职位名称
      channelPersonalReqDto.setStatus(1);//状态1启用0禁用
      return channelPersonalReqDto;
   }

   private String getChinesses(String str){
      if (StringUtils.isEmpty(str)) return null;
      String regex="([\u4e00-\u9fa5]+)";
      Matcher matcher = Pattern.compile(regex).matcher(str);
      if(matcher.find()){
         return matcher.group(0);
      }
      return null;
   }


   private ApiResult pms2CenterChannelPersonalAdd(ChannelPersonalReqDto channelPersonalReqDto) {
      RestResponse<Long> longRestResponse = null;
      try {
         longRestResponse = channelPersonalApi.addChannelPersonal(channelPersonalReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterChannelPersonalAdd_<新增渠道人员信息>-" + e.getMessage());
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterChannelPersonalAdd_<新增渠道人员信息>-" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1,"中台调用出错_pms2CenterChannelPersonalAdd_<新增渠道人员信息>-" + e.getMessage());
      }
      if (!longRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         String resultMsg = longRestResponse.getResultMsg();
         logger.error(" ------- 中台执行失败_pms2CenterChannelPersonalAdd_<新增渠道人员信息>-" + resultMsg);
         return ResponseUtil.fail(-1,"中台执行失败_pms2CenterChannelPersonalAdd_<新增渠道人员信息>-" + resultMsg);
      }
      return null;
   }

   private ApiResult pms2CenterChannelPersonalUpdate(ChannelPersonalReqDto channelPersonalReqDto) {
      RestResponse<Void> voidRestResponse = null;
      try {
         voidRestResponse = channelPersonalApi.updateChannelPersonal(channelPersonalReqDto.getAccount(), channelPersonalReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterChannelPersonalUpdate_<修改渠道人员信息>-" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_<修改渠道人员信息>___" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1,"中台调用出错_<修改渠道人员信息>___"+ e.getMessage());
      }
      if (!voidRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterChannelPersonalUpdate_<修改渠道人员信息>-" + voidRestResponse.getResultMsg());
         return ResponseUtil.fail(-1,"中台执行失败<修改渠道人员信息>___"+voidRestResponse.getResultMsg());
      }
      return null;
   }


   private boolean pms2IAM(StaffVO staffVO, String op) {
      PmsUserVO pmsUserVO = new PmsUserVO();
      ArrayList<PmsUserVO> list = new ArrayList<>();
      pmsUserVO.setAccount(staffVO.getAccountNo());
      pmsUserVO.setPassword(staffVO.getPassword());
      pmsUserVO.setPartnerCode(staffVO.getPartnerCode());
      pmsUserVO.setUserName(staffVO.getStaffName());
      pmsUserVO.setOperator(op);
      pmsUserVO.setLevel("Y");//是否管理员:Y/N
      pmsUserVO.setEmail(staffVO.getEmail());//邮箱
      pmsUserVO.setPhone(staffVO.getMobilePhone());//g管理员默认位渠道中的电话
      pmsUserVO.setOrganizationCode(staffVO.getOrgCode());//部门编码
      if (staffVO.getStatus() != null) {
         pmsUserVO.setIsEnable(String.valueOf(staffVO.getStatus()));//是否禁用
      }
      pmsUserVO.setPositionCode(staffVO.getPositionId());//职位编码
      pmsUserVO.setStatus("1");//服务商状态
      list.add(pmsUserVO);
      ApiResult apiResult = null;
      try {
         apiResult = iamDubboServiceImpl.sendIamUserVO(list);
      } catch (Exception e) {
         logger.error("  ------- pms2IAM 调用 ___人员信息  ----" + e.getMessage());
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         e.printStackTrace();
      }
      if (apiResult.getCode().equals(-1)) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- iamDubboService.sendIamUserVO 执行失败 ___人员信息  ---" + apiResult.getMsg());
         return true;
      }
      return false;
   }

   private ApiResult pms2CenterTwonetsUpdate(ChannelTwonetsReqDto channelTwonetsReqDto) {
      RestResponse<Void> voidRestResponse = null;
      try {
         voidRestResponse = channelApi.updateChannelTwonets(channelTwonetsReqDto.getTwonetsCode(), channelTwonetsReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterTwonetsUpdate ___< 修改渠道二网信息  >-----" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterTwonetsUpdate___<修改渠道二网信息>" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1,"中台调用出错_pms2CenterTwonetsUpdate___<修改渠道二网信息>"+ e.getMessage());
      }
      if (!voidRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterTwonetsUpdate ___< 修改渠道二网信息  >----" + voidRestResponse.getResultMsg());
         return ResponseUtil.fail(-1,"中台执行失败_pms2CenterTwonetsUpdate___<修改渠道二网信息>" + voidRestResponse.getResultMsg());
      }
      return null;
   }

   private ApiResult pms2CenterTwonetsAdd(ChannelTwonetsReqDto channelTwonetsReqDto) {
      RestResponse<Long> longRestResponse = null;
      try {
         longRestResponse = channelApi.addChannelTwonets(channelTwonetsReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterTwonetsAdd ___< 新增渠道二网信息  >-----" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterTwonetsAdd ___<新增渠道二网信息>" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1,"中台调用出错_pms2CenterTwonetsAdd ___<新增渠道二网信息>"+ e.getMessage());
      }
      if (!longRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterTwonetsAdd ___< 新增渠道二网信息  >--------" + longRestResponse.getResultMsg());
         return ResponseUtil.fail(-1,"中台执行失败_pms2CenterTwonetsAdd ___<新增渠道二网信息>" + longRestResponse.getResultMsg());
      }
      return null;
   }

   private void setCenterTwonets(PartnerVO partnerVO, PartnerTwonets partnerTwonet, ChannelTwonetsReqDto channelTwonetsReqDto) {
      channelTwonetsReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道商代码
      channelTwonetsReqDto.setTwonetsCode(partnerTwonet.getTwoCode());//二网代码
      channelTwonetsReqDto.setTwonetsShortName(partnerTwonet.getTwoSimpleName());//二网简称
      channelTwonetsReqDto.setTwonetsName(partnerTwonet.getTwoName());//二网名称
      channelTwonetsReqDto.setTwonetsAddr(partnerTwonet.getTwoAddr());//二网地址
      channelTwonetsReqDto.setStatus(partnerTwonet.getStatus());//状态1启用0禁用
      channelTwonetsReqDto.setCreatePerson(partnerTwonet.getCreateBy());
      channelTwonetsReqDto.setUpdatePerson(partnerTwonet.getUpdateBy());
   }

   private ApiResult pms2CenterStorangeUpdate(ChannelStorageReqDto channelStorageReqDto) {
      RestResponse<Void> voidRestResponse = null;
      try {
         voidRestResponse = channelApi.updateChannelStorage(channelStorageReqDto.getStorageCode(), channelStorageReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterStorangeUpdate ___< 修改渠道发运信息  >-" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterStorangeUpdate ___<修改渠道发运信息>-" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1,"中台调用出错_pms2CenterStorangeUpdate ___<修改渠道发运信息>-" + e.getMessage());
      }
      if (!voidRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterStorangeUpdate ___< 修改渠道发运信息  >-" + voidRestResponse.getResultMsg());
         return ResponseUtil.fail(-1,"中台执行失败_pms2CenterStorangeUpdate ___<修改渠道发运信息>-" + voidRestResponse.getResultMsg());
      }
      return null;
   }

   private ApiResult pms2CenterStorangeAdd(ChannelStorageReqDto channelStorageReqDto) {
      RestResponse<Long> longRestResponse = null;
      try {
         longRestResponse = channelApi.addChannelStorage(channelStorageReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterStorangeAdd ___< 新增渠道发运信息  >-" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterStorangeAdd___<新增渠道发运信息>-" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1,"中台调用出错_pms2CenterStorangeAdd___<新增渠道发运信息>-" + e.getMessage());
      }
      if (!longRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterStorangeAdd ___< 新增渠道发运信息  >--" + longRestResponse.getResultMsg());
         return ResponseUtil.fail(-1,"中台执行失败_pms2CenterStorangeAdd ___<新增渠道发运信息>--" + longRestResponse.getResultMsg());
      }
      return null;
   }

   private void setCenterStorage(PartnerVO partnerVO, PartnerStorage partnerStorage, ChannelStorageReqDto channelStorageReqDto) {
      channelStorageReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道编号
      channelStorageReqDto.setStorageCode(partnerStorage.getStorageCode());//仓库代码
      channelStorageReqDto.setStorageName(partnerStorage.getStorageName());//仓库名称
      channelStorageReqDto.setLinkMan(partnerStorage.getLinkMan());//联系人
      channelStorageReqDto.setLinkPhone(partnerStorage.getLinkPhone());//联系电话
      channelStorageReqDto.setStatus(partnerStorage.getStatus());//状态1启用0禁用
      channelStorageReqDto.setProvince(partnerStorage.getProvince());//省
      channelStorageReqDto.setCity(partnerStorage.getCity());//市
      channelStorageReqDto.setCounty(partnerStorage.getRegion());//区
      channelStorageReqDto.setAddress(partnerStorage.getAddr());//地址
      channelStorageReqDto.setGpsX(partnerStorage.getGpsBaiduX());//坐标x
      channelStorageReqDto.setGpsY(partnerStorage.getGpsBaiduY());//坐标y
      channelStorageReqDto.setCreatePerson(partnerStorage.getCreateBy());
      channelStorageReqDto.setUpdatePerson(partnerStorage.getUpdateBy());
   }

   private boolean pms2CenterInvoicesAdd(ChannelInvoiceReqDto channelInvoiceReqDto) {
      RestResponse<Long> longRestResponse = null;
      try {
         longRestResponse = channelApi.addChannelInvoice(channelInvoiceReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterInvoicesAdd ___< 新增渠道发票信息  >-------" + e.getMessage());
         e.printStackTrace();
         return true;
      }
      if (!longRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterInvoicesAdd ___< 新增渠道发票信息  >--------" + longRestResponse.getResultMsg());
         return true;
      }
      return false;
   }

   private boolean pms2CenterInvoicesUpdate(ChannelInvoiceReqDto channelInvoiceReqDto) {
      RestResponse<Void> voidRestResponse = null;
      try {
         voidRestResponse = channelApi.updateChannelInvoice(channelInvoiceReqDto.getInvoiceCode(), channelInvoiceReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterInvoicesUpdate ___< 修改渠道发票信息  >--------" + e.getMessage());
         e.printStackTrace();
         return true;
      }
      if (!voidRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterInvoicesUpdate ___< 修改渠道发票信息  >--------" + voidRestResponse.getResultMsg());
         return true;
      }
      return false;
   }

   private void setCenterInvoice(PartnerVO partnerVO, PartnerInvoice partnerInvoice, ChannelInvoiceReqDto channelInvoiceReqDto) {
      if ("pms".equals(partnerVO.getTenantId())){
//      channelInvoiceReqDto.setInvoiceCode(partnerInvoice.getInvoiceCode());//开票信息编码

         channelInvoiceReqDto.setInvoiceCode(partnerVO.getPartnerCode() + "_" + partnerInvoice.getInvoiceId());//开票信息编码

         channelInvoiceReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道代码
         channelInvoiceReqDto.setBankName(partnerInvoice.getBank());//开户银行
         channelInvoiceReqDto.setBankAccount(partnerInvoice.getBankAccount());//开户帐号
         channelInvoiceReqDto.setTitleName(partnerInvoice.getTitle());//开票名称
         channelInvoiceReqDto.setRegAddr(partnerInvoice.getBankAdd());//注册地址
         channelInvoiceReqDto.setStatus(partnerInvoice.getStatus());//状态1启用0禁用
         channelInvoiceReqDto.setCreatePerson(partnerInvoice.getCreateBy());
         channelInvoiceReqDto.setUpdatePerson(partnerInvoice.getUpdateBy());
         channelInvoiceReqDto.setBankCode(partnerInvoice.getBankCode());//银行国家代码
         channelInvoiceReqDto.setBankNo(partnerInvoice.getBankNo());//银行编号
         channelInvoiceReqDto.setBankHolder(partnerInvoice.getBankHolder());//帐户持有人姓名
         channelInvoiceReqDto.setBankEmail(partnerInvoice.getBankEmail());//银行邮箱
      }else {
         channelInvoiceReqDto.setInvoiceCode(partnerVO.getPartnerCode() + "_" + partnerInvoice.getInvoiceId());//开票信息编码

         channelInvoiceReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道代码
         channelInvoiceReqDto.setBankCode(partnerInvoice.getBankCode());//银行国家代码
         channelInvoiceReqDto.setBankName(partnerInvoice.getBank());//开户银行
         channelInvoiceReqDto.setBankAccount(partnerInvoice.getBankAccount());//开户帐号
         channelInvoiceReqDto.setAccountCompany(partnerInvoice.getAccountCompany());//账户持有公司
         channelInvoiceReqDto.setTaxNo(partnerInvoice.getTaxNo());//税号
         channelInvoiceReqDto.setBillingAddress(partnerInvoice.getBillingAddress());//开票地址
         channelInvoiceReqDto.setBillingLinkman(partnerInvoice.getBillingLinkman());//开票联系人
         channelInvoiceReqDto.setBillingPhone(partnerInvoice.getBillingPhone());
      }
   }

   private ApiResult pms2CenterUpdate(PartnerVO partnerVO, ChannelReqDto channelReqDto) {
      RestResponse<Void> voidRestResponse = null;
      try {
         //将渠道信息传入中台
         voidRestResponse = channelApi.updateChannel(partnerVO.getPartnerCode(), channelReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterUpdate ___< 修改渠道基本信息  >--------" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterUpdate___<修改渠道基本信息>-----" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1, "中台调用出错_pms2CenterUpdate___<修改渠道基本信息>-----" + e.getMessage());
      }
      if (!voidRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterUpdate ___< 修改渠道基本信息  >--------" + voidRestResponse.getResultMsg());
         return ResponseUtil.fail(-1, "中台执行失败_pms2CenterUpdate___<修改渠道基本信息>--------" + voidRestResponse.getResultMsg());
      }
      return null;
   }

   private ApiResult pms2CenterAdd(ChannelReqDto channelReqDto) {
      RestResponse<Long> longRestResponse = null;
      try {
         //将渠道信息传入中台
         longRestResponse = channelApi.addChannel(channelReqDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterAdd ___< 新增渠道基本信息  >--------" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterAdd___< 新增渠道基本信息  >--------" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1, "中台调用出错_pms2CenterAdd___< 新增渠道基本信息  >--------" + e.getMessage());
      }
      if (!longRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterAdd ___< 新增渠道基本信息  >--------" + longRestResponse.getResultMsg());
         return ResponseUtil.fail(-1, "中台执行失败_pms2CenterAdd ___< 新增渠道基本信息  >--------" + longRestResponse.getResultMsg());
      }
      return null;
   }


   private ApiResult pms2SAP(PartnerVO partnerVO, String op) {
      PartnerInfoVO partnerInfoVO = setPropPartnerInfoVO(partnerVO);

      setOrgInfo(partnerVO, partnerInfoVO, null, "1");

      partnerInfoVO.setIndicator(op);
      ApiResult apiResult1 = null;
      try {
         apiResult1 = sapDubboServiceImpl.savePartnerInfoToSap(partnerInfoVO);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- pms2SAP 调用失败 ___渠道信息  --------" + e.getMessage());
         e.printStackTrace();
         return ResponseUtil.fail(-1, "pms2SAP 调用失败 ___渠道信息  --------" + e.getMessage());
      }
      if (apiResult1.getCode().equals(-1)) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- pms2SAP 执行失败 ___渠道信息  --------" + apiResult1.getMsg());
         return ResponseUtil.fail(-1, "pms2SAP 执行失败 ___渠道信息 -----" + apiResult1.getMsg());
      }
      return null;
   }

   private ApiResult pms2SAP2(PartnerVO partnerVO, String op) {
      String partnerType = partnerService.getPartnerType(partnerVO.getPartnerCode());
      if ("pms".equals(partnerType)){
         partnerType = "1";
      }else if ("ups".equals(partnerType)){
         partnerType = "2";
      }
      PartnerInfoVO partnerInfoVO = setPropPartnerInfoVO2(partnerVO,partnerType);

      setOrgInfo(partnerVO, partnerInfoVO, null, partnerType);

      partnerInfoVO.setIndicator(op);
      ApiResult apiResult1 = null;
      try {
         apiResult1 = sapDubboServiceImpl.savePartnerInfoToSap(partnerInfoVO);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- pms2SAP2(PartnerVO partnerVO, String op) 调用失败 ___渠道信息  --------" + e.getMessage());
         e.printStackTrace();
         return ResponseUtil.fail(-1,"pms2SAP2调用失败渠道信息"+op+"____"+e.getMessage());
      }
      if (apiResult1.getCode().equals(-1)) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- pms2SAP2(PartnerVO partnerVO, String op) 执行失败 ___渠道信息  --------" + apiResult1.getMsg());
         return ResponseUtil.fail(-1,"pms2SAP2执行失败渠道信息"+op+"____"+apiResult1.getMsg());
      }
      return null;
   }

   private boolean pms2SAPInvoice(PartnerInvoice partnerInvoice, String op) {
      PartnerInfoVO partnerInfoVO = setPropPartnerInfoVOInvocie(partnerInvoice);

      //setOrgInfo(partnerVO, partnerInfoVO, null, "1");

      partnerInfoVO.setIndicator(op);
      ApiResult apiResult1 = null;
      try {
         apiResult1 = sapDubboServiceImpl.savePartnerInfoToSap(partnerInfoVO);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- pms2SAPInvoice(PartnerInvoice partnerInvoice, String op) 调用失败 ___渠道发票信息  -------" + e.getMessage());
         e.printStackTrace();
      }
      if (apiResult1.getCode().equals(-1)) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- sapDubboServiceImpl.savePartnerInfoToSap 执行失败 ___渠道发票信息  --------" + apiResult1.getMsg());
         return true;
      }
      return false;
   }

   private ApiResult pms2SAP2(PartnerVO partnerVO, PartnerInfoVO partnerInfoVO, String op) {
      setOrgInfo(partnerVO, partnerInfoVO, partnerVO.getPartnerCode(), "1");

      partnerInfoVO.setIndicator(op);
      ApiResult apiResult1 = null;
      try {
         apiResult1 = sapDubboServiceImpl.savePartnerInfoToSap(partnerInfoVO);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- pms2SAP2(PartnerVO partnerVO, PartnerInfoVO partnerInfoVO, String op) 调用失败 ___渠道信息  --------" + e.getMessage());
         e.printStackTrace();
         return ResponseUtil.fail(-1,"pms2SAP2调用失败"+ e.getMessage());
      }
      if (apiResult1.getCode().equals(-1)) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- pms2SAP2(PartnerVO partnerVO, PartnerInfoVO partnerInfoVO, String op) 执行失败 ___渠道信息  -------" + apiResult1.getMsg());
         return ResponseUtil.fail(-1,"执行失败"+ apiResult1.getMsg());
      }
      return null;
   }

   private void setOrgInfo(PartnerVO partnerVO, PartnerInfoVO partnerInfoVO, String superCode, String type) {
      partnerInfoVO.setZobl1(superCode);//上级渠道CODE
      partnerInfoVO.setZobl2(partnerVO.getStatus() + "");//渠道状态
      partnerInfoVO.setZobl3(WgrDate.getCurrentTime(3));//修改时间
      //partnerInfoVO.setZobl4();//备注
      partnerInfoVO.setType(type);//类型状态 1渠道商，2物流公司

      /*ApiResult apiResult1 = sapDubboServiceImpl.savePartnerInfoToSap(partnerInfoVO);
      if (apiResult1.getCode().equals(-1)) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error("  ------- sapDubboServiceImpl.savePartnerInfoToSap 执行失败 ___组织机构信息  ---------  ");
         return true;
      }
      return false;*/
   }

   //设置sap渠道 +银行 属性
   private PartnerInfoVO setPropPartnerInfoVO(PartnerVO partnerVO) {
      PartnerInfoVO partnerInfoVO = new PartnerInfoVO();
      //图片
      List<AttachVO> imageVOList = partnerVO.getImageVOList();
      if (imageVOList!=null && imageVOList.size()>0){
         List<PartnerImgVO> partnerImgVOS = new ArrayList<>();
         for (AttachVO attachVO : imageVOList) {
            PartnerImgVO partnerImgVO = new PartnerImgVO();
            partnerImgVO.setImgUrl(attachVO.getPicPath());
            partnerImgVOS.add(partnerImgVO);
         }
         partnerInfoVO.setImgList(partnerImgVOS);
      }
      if ("pms".equals(partnerVO.getTenantId())) {
         partnerInfoVO.setKunnr(partnerVO.getPartnerCode());
         partnerInfoVO.setKtokd(partnerVO.getAccountGroupCode());
         partnerInfoVO.setName1(partnerVO.getPartnerName());
         partnerInfoVO.setSortl(partnerVO.getPartnerSimpleName());
         partnerInfoVO.setStras(partnerVO.getAddr());
         partnerInfoVO.setPstlz(partnerVO.getPostalCode());
         partnerInfoVO.setCounc(partnerVO.getCountry());
         partnerInfoVO.setRegio(partnerVO.getProvince());
         partnerInfoVO.setBezei(partnerVO.getProvince());
         partnerInfoVO.setOrt01((partnerVO.getCity()));
         partnerInfoVO.setTelf1(partnerVO.getLinkPhone());
         partnerInfoVO.setMobil(partnerVO.getMobilePhone());
         partnerInfoVO.setTelfx(partnerVO.getFax());
         partnerInfoVO.setEmail(partnerVO.getEntwepriseMailbox());
         partnerInfoVO.setIdnumber2(partnerVO.getUnionCreditCode());
         partnerInfoVO.setContact(partnerVO.getLinkMan());
         partnerInfoVO.setVkorg(partnerVO.getParentCompanyCode());
         partnerInfoVO.setSelfs(partnerVO.getIsAfhalen());
         partnerInfoVO.setDirect(partnerVO.getIsDirectSending());
         partnerInfoVO.setAkont(partnerVO.getAkont());
         partnerInfoVO.setStatus(partnerVO.getStatus() + "");
         partnerInfoVO.setLongitude(partnerVO.getGpsX());
         partnerInfoVO.setDimension(partnerVO.getGpsY());
         if ("010".equals(partnerVO.getBusinessCode())){
            partnerInfoVO.setPartnerType("3");    //	渠道类型
         }else {
            partnerInfoVO.setPartnerType("1");    //	渠道类型
         }
         partnerInfoVO.setBizTyoe(partnerVO.getBusinessCode());//业务类型

         List<PartnerTypeVO> partnerTypeVOList = partnerVO.getPartnerTypeVOList();
//         if (partnerTypeVOList != null && partnerTypeVOList.size() > 0) {
            partnerInfoVO.setIssale("Y");//是否销售
            partnerInfoVO.setIsRepair("N");//是否售后
            partnerInfoVO.setIsDrive("Y");//是否试驾
            partnerInfoVO.setIsdeliver("Y");//是否交车
//            for (PartnerTypeVO partnerTypeVO : partnerTypeVOList) {
//
//               if (partnerTypeVO.getAccountGroupCode().equals("Y005")) {
//
//               }
//               if (partnerTypeVO.getAccountGroupCode().equals("Y008")) {
//
//               }
//            }
//         }

         List<BankVO> list = new ArrayList<>();
         for (PartnerInvoiceVO partnerInvoiceVO : partnerVO.getPartnerInvoiceVOList()) {
            BankVO bankVO = new BankVO();
            bankVO.setKunnr(partnerVO.getPartnerCode());
            bankVO.setBanks(partnerInvoiceVO.getBankCode());
            bankVO.setBankl(partnerInvoiceVO.getBankNo());
            bankVO.setBankn(partnerInvoiceVO.getBankAccount());
            bankVO.setKoinh(partnerInvoiceVO.getBankHolder());
            bankVO.setBanka(partnerInvoiceVO.getBank());
            bankVO.setBankemail(partnerInvoiceVO.getBankEmail());
            bankVO.setStreet(partnerInvoiceVO.getBankAdd());
            list.add(bankVO);
         }
         partnerInfoVO.setBank(list);

      } else {
         //UPS渠道商
         partnerInfoVO.setKunnr(partnerVO.getPartnerCode());//渠道商编号
         partnerInfoVO.setName1(partnerVO.getCompanyName());//售后公司名称
         partnerInfoVO.setIdnumber2(partnerVO.getUnionCreditCode());//统一社会信用代码
         partnerInfoVO.setEmail(partnerVO.getEntwepriseMailbox());//Email
         partnerInfoVO.setTelf1(partnerVO.getPhone());//电话
         partnerInfoVO.setStras(partnerVO.getAddr());//地址
         partnerInfoVO.setCounc(partnerVO.getCountry());//国家
         partnerInfoVO.setRegio(partnerVO.getProvince());//省编码
//         partnerInfoVO.setBezei(partnerVO.);//省名称
         partnerInfoVO.setOrt01(partnerVO.getCity());//市编码
         partnerInfoVO.setDistrictCode(partnerVO.getRegion());//	区/县编码
         if (partnerVO.getStatus()!=null){
            partnerInfoVO.setZobl2(String.valueOf(partnerVO.getStatus()));//状态 1入网 2退网 3冻结
         }
         partnerInfoVO.setShortName(partnerVO.getPartnerSimpleName());//网点简称
         partnerInfoVO.setUsedName(partnerVO.getBeforName());//网点曾用名
         partnerInfoVO.setRegionCode(partnerVO.getCity());    //	区域
         partnerInfoVO.setRegionPersonnel(partnerVO.getAreaManger());    //	区域负责人
         partnerInfoVO.setFunctionType(partnerVO.getFunctionType());    //	功能类型（服务中心/服务空间）
         partnerInfoVO.setBranchType(partnerVO.getBranchType());    //	网点类型（9号馆/2号馆）
         partnerInfoVO.setCompanyName(partnerVO.getCompanyName());    // 	公司名称
         partnerInfoVO.setBusinessLicenseAddress(partnerVO.getBusinessLicenseAddress());//	营业执照地址
         partnerInfoVO.setBusinessAddress(partnerVO.getAddr());    //	公司经营地址
         partnerInfoVO.setLongitude(partnerVO.getGpsX()); //经度
         partnerInfoVO.setLatitude(partnerVO.getGpsY()); //	纬度
         partnerInfoVO.setDeliveryAddress(partnerVO.getDeliveryAddress());//送货地址
         partnerInfoVO.setPostCode(partnerVO.getPostalCode());    //	邮编
         partnerInfoVO.setFirstLinkman(partnerVO.getFirstLintman());    //	送货第一联系人
         partnerInfoVO.setFirstPhone(partnerVO.getFirstPhone());    //	送货人联系方式
         partnerInfoVO.setSecondLinkman(partnerVO.getSecondLintman());    //	送货第二联系人
         partnerInfoVO.setSecondPhone(partnerVO.getSecondPhone());    //	送货人联系方式
         partnerInfoVO.setMaintenanceQualification(partnerVO.getMaintenanceQualification());//维修资质
         partnerInfoVO.setBusinessDate(partnerVO.getBusinessDate());   //营业时间（周一至周日）
         partnerInfoVO.setBusinessTime(partnerVO.getBusinessTime());  //营业时间（9:00~21:00）
         partnerInfoVO.setFixPhone(partnerVO.getFixPhone());    //	网点服务电话（固话）
         partnerInfoVO.setContractMailingAddress(partnerVO.getContractMailingAddress());//合同/协议邮寄地址
         partnerInfoVO.setLinkman(partnerVO.getLinkMan());    //	联系人
         partnerInfoVO.setPhone(partnerVO.getPhone());    //	电话

         partnerInfoVO.setPartnerType("2");    //	渠道类型
         partnerInfoVO.setCapacitance(partnerVO.getCapacitance());    //	富余电容（Kw）
         partnerInfoVO.setChargingPileDesc(partnerVO.getChargingPileDesc());    //	"现有普通充电桩数量及功率（交流，慢充）"
         partnerInfoVO.setFastChargeDesc(partnerVO.getFastChargeDesc());    //	"现有快充桩数量及功率（直流，快充）"

         partnerInfoVO.setVkorg(partnerVO.getParentCompanyCode());
         partnerInfoVO.setSelfs(partnerVO.getIsAfhalen());
         partnerInfoVO.setDirect(partnerVO.getIsDirectSending());

         List<BankVO> list = new ArrayList<>();
         for (PartnerInvoiceVO partnerInvoiceVO : partnerVO.getPartnerInvoiceVOList()) {
            BankVO bankVO = new BankVO();
            bankVO.setKunnr(partnerVO.getPartnerCode());//客户号
            bankVO.setBanks(partnerInvoiceVO.getBankCode());//银行国家代码
            bankVO.setBankl(partnerInvoiceVO.getBankNo());//银行编号
            bankVO.setBankn(partnerInvoiceVO.getBankAccount());//银行账户
            bankVO.setKoinh(partnerInvoiceVO.getBankHolder());//帐户持有人姓名
            bankVO.setBanka(partnerInvoiceVO.getBank());//银行名称
            bankVO.setBankemail(partnerInvoiceVO.getBankEmail());//银行邮箱
            bankVO.setStreet(partnerInvoiceVO.getBankAdd());//银行地址

            partnerInfoVO.setAccountCompany(partnerInvoiceVO.getAccountCompany());    //账户持有公司
            partnerInfoVO.setTaxNo(partnerInvoiceVO.getTaxNo());    //税号
            partnerInfoVO.setBillingAddress(partnerInvoiceVO.getBillingAddress());    //开票地址
            partnerInfoVO.setInvoiceAddress(partnerInvoiceVO.getInvoiceAddress());    //发票快递地址
            partnerInfoVO.setBillingLinkman(partnerInvoiceVO.getBillingLinkman());    //开票联系人
            partnerInfoVO.setBillingPhone(partnerInvoiceVO.getBillingPhone());    //	开票联系电话

            partnerInfoVO.setBanks(partnerInvoiceVO.getBankCode());    //	开户银行代码
            partnerInfoVO.setBanka(partnerInvoiceVO.getBank());    //	开户银行名称
            partnerInfoVO.setBankn(partnerInvoiceVO.getBankAccount());    //	银行帐号
            list.add(bankVO);
         }
         partnerInfoVO.setBank(list);

         partnerInfoVO.setIssale("N");//是否销售
         partnerInfoVO.setIsRepair("Y");//是否售后
         partnerInfoVO.setIsDrive("N");//是否试驾
         partnerInfoVO.setIsdeliver("N");//是否交车
      }
      return partnerInfoVO;
   }

   //设置sap渠道属性
   private PartnerInfoVO setPropPartnerInfoVO2(PartnerVO partnerVO,String partnerType) {
      PartnerInfoVO partnerInfoVO = new PartnerInfoVO();
      partnerInfoVO.setKunnr(partnerVO.getPartnerCode());
      partnerInfoVO.setKtokd(partnerVO.getAccountGroupCode());
      partnerInfoVO.setName1(partnerVO.getPartnerName());
      partnerInfoVO.setSortl(partnerVO.getPartnerSimpleName());
      partnerInfoVO.setStras(partnerVO.getAddr());
      partnerInfoVO.setPstlz(partnerVO.getPostalCode());
      partnerInfoVO.setCounc(partnerVO.getCountry());
      partnerInfoVO.setRegio(partnerVO.getProvince());
      partnerInfoVO.setBezei(partnerVO.getProvince());
      partnerInfoVO.setOrt01((partnerVO.getCity()));
      partnerInfoVO.setTelf1(partnerVO.getLinkPhone());
      partnerInfoVO.setMobil(partnerVO.getMobilePhone());
      partnerInfoVO.setTelfx(partnerVO.getFax());
      partnerInfoVO.setEmail(partnerVO.getEntwepriseMailbox());
      partnerInfoVO.setIdnumber2(partnerVO.getUnionCreditCode());
      partnerInfoVO.setContact(partnerVO.getLinkMan());
      partnerInfoVO.setVkorg(partnerVO.getParentCompanyCode());
      partnerInfoVO.setSelfs(partnerVO.getIsAfhalen());
      partnerInfoVO.setDirect(partnerVO.getIsDirectSending());
      partnerInfoVO.setAkont(partnerVO.getAkont());
      partnerInfoVO.setStatus(partnerVO.getStatus() + "");
      partnerInfoVO.setLongitude(partnerVO.getGpsX());
      partnerInfoVO.setDimension(partnerVO.getGpsY());
      partnerInfoVO.setPartnerType(partnerType);

      return partnerInfoVO;
   }

   private PartnerInfoVO setPropPartnerInfoVOInvocie(PartnerInvoice partnerInvoice) {

      List<BankVO> list = new ArrayList<>();

      BankVO bankVO = new BankVO();
      bankVO.setKunnr(partnerInvoice.getPartnerCode());
      bankVO.setBanks(partnerInvoice.getBankCode());
      bankVO.setBankl(partnerInvoice.getBankNo());
      bankVO.setBankn(partnerInvoice.getBankAccount());
      bankVO.setKoinh(partnerInvoice.getBankHolder());
      bankVO.setBanka(partnerInvoice.getBank());
      bankVO.setBankemail(partnerInvoice.getBankEmail());
      bankVO.setStreet(partnerInvoice.getBankAdd());
      list.add(bankVO);
      PartnerInfoVO partnerInfoVO = new PartnerInfoVO();
      partnerInfoVO.setBank(list);
      return partnerInfoVO;
   }

   //设置中台属性
   private void setProp(PartnerVO partnerVO, ChannelReqDto channelReqDto) {
      //销售渠道商
      if ("pms".equals(partnerVO.getTenantId())) {
         channelReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道代码
         channelReqDto.setChannelShortName(partnerVO.getPartnerSimpleName());//渠道简称
         channelReqDto.setChannelName(partnerVO.getPartnerName());//渠道名称
         //channelReqDto.setSupplierCode();//上级企业编号
         channelReqDto.setBizType(partnerVO.getBusinessCode());//业务类型:销售业务，租聘业务，售后业务
         channelReqDto.setPartnerType(partnerVO.getAccountGroupCode());//渠道伙伴类型： Y005 零售伙伴 Y008 交付伙伴 Y009 电商伙伴 Y010 直客客户 Y012 批售伙伴
         //partnerTypeName//渠道伙伴类型名称：零售类型，交付类型，电商类型，直客类型，批售类型
         channelReqDto.setChannelLevel(partnerVO.getPartnerLevel());//渠道商级别

         channelReqDto.setLegalPerson(partnerVO.getLegalPerson());//法人代表
         channelReqDto.setLinkName(partnerVO.getLinkMan());//联系人
         channelReqDto.setLinkTel(partnerVO.getLinkPhone());//联系电话
         channelReqDto.setLinkPhone(partnerVO.getMobilePhone());//手机号
         channelReqDto.setFax(partnerVO.getFax());//企业传真
         channelReqDto.setEmail(partnerVO.getEntwepriseMailbox());//企业邮箱
         channelReqDto.setCreditCode(partnerVO.getUnionCreditCode());//统一信用代码
         //servicePhone//服务热线
         //salesPhone//销售热线
         channelReqDto.setSalesOrganize(partnerVO.getParentCompanyCode());//销售组织
         channelReqDto.setProductAuthCode(partnerVO.getProductAuthCodeJson());//产品授权
         channelReqDto.setCheckPerson(partnerVO.getCheckPerson());//验收人
         channelReqDto.setCheckTime(partnerVO.getCheckTime());//验收时间
         channelReqDto.setStatus(partnerVO.getStatus());//渠道商状态1：入网；2 ：退网 3：冻结
         channelReqDto.setStatusTime(partnerVO.getRunStatusChangetime());//运营状态更改时间
         channelReqDto.setIsSelfTake(partnerVO.getIsAfhalen());//是否自提
         channelReqDto.setIsDirectDelivery(partnerVO.getIsDirectSending());//是否直送
         channelReqDto.setNation(partnerVO.getCountry());//国家
         channelReqDto.setProvince(partnerVO.getProvince());//省
         channelReqDto.setCity(partnerVO.getCity());//市
         channelReqDto.setCounty(partnerVO.getRegion());//区
         channelReqDto.setAddress(partnerVO.getAddr());//地址
         channelReqDto.setGpsX(partnerVO.getGpsX());//坐标x
         channelReqDto.setGpsY(partnerVO.getGpsY());//坐标y
         channelReqDto.setChannelProps(new HashSet<>(partnerVO.getAccountPropCodeList()));//渠道商属性编码
         channelReqDto.setCreatePerson(partnerVO.getCreateBy());
         channelReqDto.setUpdatePerson(partnerVO.getUpdateBy());
         channelReqDto.setPostCode(partnerVO.getPostalCode());//邮政编码
         channelReqDto.setAkont(partnerVO.getAkont());//统驭科目
      }else {
         channelReqDto.setBizType("AFTELSELL");//业务类型:销售业务，租聘业务，售后业务
         channelReqDto.setPartnerType("Y005");//渠道伙伴类型： Y005 零售伙伴 Y008 交付伙伴 Y009 电商伙伴 Y010 直客客户 Y012 批售伙伴
         //售后渠道商
         channelReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道代码
         channelReqDto.setChannelShortName(partnerVO.getPartnerSimpleName());//渠道简称
         channelReqDto.setBeforName(partnerVO.getBeforName());//网点曾用名
         channelReqDto.setWarzone(partnerVO.getRegionCode());//区域
         channelReqDto.setRegionPersonnel(partnerVO.getAreaManger());//区域负责人
         channelReqDto.setFunctionType(partnerVO.getFunctionType());//功能类型(服务中心/服务空间)
         channelReqDto.setBranchType(partnerVO.getBranchType());//网点类型
         channelReqDto.setProvince(partnerVO.getProvince());
         channelReqDto.setCity(partnerVO.getCity());
         channelReqDto.setCounty(partnerVO.getRegion());
         channelReqDto.setChannelName(partnerVO.getCompanyName());//公司名称
         channelReqDto.setCreditCode(partnerVO.getUnionCreditCode());//统一信用代码
         channelReqDto.setBusinessLicenseAddress(partnerVO.getBusinessLicenseAddress());//营业执照地址
         channelReqDto.setAddress(partnerVO.getAddr());//公司经营地址
         channelReqDto.setGpsX(partnerVO.getGpsX());
         channelReqDto.setGpsY(partnerVO.getGpsY());
         channelReqDto.setDeliveryAddress(partnerVO.getDeliveryAddress());//送货地址
         channelReqDto.setPostCode(partnerVO.getPostalCode());//邮政编码
         channelReqDto.setFirstLintman(partnerVO.getFirstLintman());//送货第一联系人
         channelReqDto.setFirstPhone(partnerVO.getFirstPhone());//送货第一联系人联系方式
         channelReqDto.setSecondLintman(partnerVO.getSecondLintman());//送货第二联系人
         channelReqDto.setSecondPhone(partnerVO.getSecondPhone());//送货第二联系人联系方式
         channelReqDto.setMaintenanceQualification(partnerVO.getMaintenanceQualification());//维修资质
         channelReqDto.setBusinessDate(partnerVO.getBusinessDate());//营业时间(周一至周日)
         channelReqDto.setBusinessTime(partnerVO.getBusinessTime());//营业时间(9:00~21:00)
         channelReqDto.setFixPhone(partnerVO.getFixPhone());//网点服务电话
         channelReqDto.setContractMailingAddress(partnerVO.getContractMailingAddress());//合同/协议邮寄地址
         channelReqDto.setLinkName(partnerVO.getLinkMan());//联系人
         channelReqDto.setLinkPhone(partnerVO.getLinkPhone());//电话
         channelReqDto.setCapacitance(partnerVO.getCapacitance());//富余电容
         channelReqDto.setChargingPileDesc(partnerVO.getChargingPileDesc());//现有普通充电桩数量及功率
         channelReqDto.setFastChargeDesc(partnerVO.getFastChargeDesc());//现有快充桩数量及功率


      }
//      //渠道开票信息
//      List<PartnerInvoiceVO> partnerInvoiceVOList1 = partnerVO.getPartnerInvoiceVOList();
//      ArrayList<ChannelInvoiceReqDto> channelInvoiceReqDtos = new ArrayList<>();
//      for (PartnerInvoiceVO partnerInvoiceVO : partnerInvoiceVOList1) {
//         ChannelInvoiceReqDto channelInvoiceReqDto = new ChannelInvoiceReqDto();
//
//         channelInvoiceReqDto.setInvoiceCode(partnerInvoiceVO.getInvoiceCode());//开票信息编码
//         channelInvoiceReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道代码
//         channelInvoiceReqDto.setBankName(partnerInvoiceVO.getBank());//开户银行
//         channelInvoiceReqDto.setBankAccount(partnerInvoiceVO.getBankAccount());//开户帐号
//         channelInvoiceReqDto.setTitleName(partnerInvoiceVO.getTitle());//开票名称
//         //brandId//品牌ID
//         //taxNo//税号
//         channelInvoiceReqDto.setRegAddr(partnerInvoiceVO.getBankAdd());//注册地址
//         channelInvoiceReqDto.setStatus(partnerInvoiceVO.getStatus());//状态1启用0禁用
//         channelInvoiceReqDto.setCreatePerson(partnerInvoiceVO.getCreateBy());
//         channelInvoiceReqDto.setUpdatePerson(partnerInvoiceVO.getUpdateBy());
//         channelInvoiceReqDtos.add(channelInvoiceReqDto);
//      }
//      channelReqDto.setChannelInvoiceReqDtos(channelInvoiceReqDtos);
//      //渠道仓库信息
//      List<PartnerStorageVO> partnerStorageVOList1 = partnerVO.getPartnerStorageVOList();
//      ArrayList<ChannelStorageReqDto> channelStorageReqDtos = new ArrayList<>();
//      for (PartnerStorageVO partnerStorageVO : partnerStorageVOList1) {
//         ChannelStorageReqDto channelStorageReqDto = new ChannelStorageReqDto();
//
//         channelStorageReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道编号
//         channelStorageReqDto.setStorageCode(partnerStorageVO.getStorageCode());//仓库代码
//         channelStorageReqDto.setStorageName(partnerStorageVO.getStorageName());//仓库名称
//         channelStorageReqDto.setLinkMan(partnerStorageVO.getLinkMan());//联系人
//         channelStorageReqDto.setLinkPhone(partnerStorageVO.getLinkPhone());//联系电话
//         channelStorageReqDto.setStatus(partnerStorageVO.getStatus());//状态1启用0禁用
//         channelStorageReqDto.setProvince(partnerStorageVO.getProvince());//省
//         channelStorageReqDto.setCity(partnerStorageVO.getCity());//市
//         channelStorageReqDto.setCounty(partnerStorageVO.getRegion());//区
//         channelStorageReqDto.setAddress(partnerStorageVO.getAddr());//地址
//         channelStorageReqDto.setGpsX(partnerStorageVO.getGpsBaiduX());//坐标x
//         channelStorageReqDto.setGpsY(partnerStorageVO.getGpsBaiduY());//坐标y
//         channelStorageReqDto.setCreatePerson(partnerStorageVO.getCreateBy());
//         channelStorageReqDto.setUpdatePerson(partnerStorageVO.getUpdateBy());
//         channelStorageReqDtos.add(channelStorageReqDto);
//      }
//      channelReqDto.setChannelStorageReqDtos(channelStorageReqDtos);
//      //渠道二网信息
//      List<PartnerTwonetsVO> partnerTwonetsVOList1 = partnerVO.getPartnerTwonetsVOList();
//      ArrayList<ChannelTwonetsReqDto> channelTwonetsReqDtos = new ArrayList<>();
//      for (PartnerTwonetsVO partnerTwonetsVO : partnerTwonetsVOList1) {
//         ChannelTwonetsReqDto channelTwonetsReqDto = new ChannelTwonetsReqDto();
//
//         channelTwonetsReqDto.setChannelCode(partnerVO.getPartnerCode());//渠道商代码
//         channelTwonetsReqDto.setTwonetsCode(partnerTwonetsVO.getTwoCode());//二网代码
//         channelTwonetsReqDto.setTwonetsShortName(partnerTwonetsVO.getTwoSimpleName());//二网简称
//         channelTwonetsReqDto.setTwonetsName(partnerTwonetsVO.getTwoName());//二网名称
//         channelTwonetsReqDto.setTwonetsAddr(partnerTwonetsVO.getTwoAddr());//二网地址
//         channelTwonetsReqDto.setStatus(partnerTwonetsVO.getStatus());//状态1启用0禁用
//         channelTwonetsReqDto.setCreatePerson(partnerTwonetsVO.getCreateBy());
//         channelTwonetsReqDto.setUpdatePerson(partnerTwonetsVO.getUpdateBy());
//         channelTwonetsReqDtos.add(channelTwonetsReqDto);
//      }
//      channelReqDto.setChannelTwonetsReqDtos(channelTwonetsReqDtos);
   }

   @Override
   public void removeById(String id) throws Exception {
      //Partner partner = partnerService.getById(id);
      partnerService.removeById(id);
      /*PartnerVO partnerVO = new PartnerVO();
      BeanUtils.copyProperties(partner, partnerVO);
      ApiResult apiResult = this.pms2sap(partnerVO, S2SEnums.OperatorType.delete.getKey());
      if(apiResult.getCode().equals(-1)){
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }*/
   }

   @Override
   public PageInfo<PartnerVO> findPageByVO(PartnerVO partnerVO, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {
      return partnerService.pageByVo(partnerVO, pageNum, pageSize);
   }

   @Override
   public PartnerVO load(String partnerCode,String tenantId) {
      PartnerVO partnerVO = partnerService.load(partnerCode,tenantId);
      if(partnerVO != null){
         List<AttachVO> imageVOList = partnerVO.getImageVOList();
         AttachVO attachVO = new AttachVO();
         attachVO.setBusId("pms_partner_img");
         attachVO.setBusSubId(partnerCode);
         List<AttachVO> list = sysAttachService.listByVo(attachVO);
         if (list!=null && list.size()>0){
            for (AttachVO vo : list) {
               imageVOList.add(vo);
            }
         }
      }
      return partnerVO;
   }


   private ApiResult updateUserStatus(PartnerVO partnerVO, Integer status, Integer isOpen,LoginInfo login) throws Exception {
      StaffVO staffVO = new StaffVO();
      staffVO.setPartnerCode(partnerVO.getPartnerCode());
      List<StaffVO> list = staffDubboServiceImpl.listByVO(staffVO,login);
      if (list != null && list.size() > 0) {
         for (StaffVO vo : list) {
            String accountNo = vo.getAccountNo();
            HashMap<String, Object> map = new HashMap<>();
            map.put("userCode", accountNo);
            UserVO user = userDubboServiceImpl.findUserByUserCode(map);
            user.setStatus(status);
            user.setIsOpen(isOpen);
            userDubboServiceImpl.update(user);
            //更改人员状态
            if (status == 2) {  //退网
               vo.setStatus(0);
               ChannelPersonalReqDto channelPersonalReqDto = setChannelPersonalReqDto(vo);
               //传入中台 修改渠道人员信息
               ApiResult result = pms2CenterChannelPersonalUpdate(channelPersonalReqDto);
               if (result!=null) return result;
               LoginInfo loginInfo = new LoginInfo();
               staffDubboServiceImpl.saveOrUpdate(vo, loginInfo);
            }

         }
      }
      return null;
   }

   private ApiResult pms2CenterUpdateStatus(PartnerVO partnerVO) {
      ChannelBaseDto channelBaseDto = new ChannelBaseDto();
      channelBaseDto.setUpdatePerson(partnerVO.getUpdateBy());
      RestResponse<Void> voidRestResponse = null;
      String flag = null; //retireNet：退网， frozen：冻结， enable：启用
      if (partnerVO.getStatus().equals(1)) {//入网
         flag = "enable";
      }
      if (partnerVO.getStatus().equals(2)) {//退网
         flag = "retireNet";
      }
      if (partnerVO.getStatus().equals(3)) {//冻结
         flag = "frozen";
      }
      if (StringUtils.isEmpty(flag)) ResponseUtil.fail(-1,"渠道商状态为空",+partnerVO.getStatus());
      try {
         voidRestResponse = channelApi.updateChannelStatus(flag, partnerVO.getPartnerCode(), channelBaseDto);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台调用出错_pms2CenterUpdateStatus ___< 修改渠道状态  >--------" + e.getMessage());
         e.printStackTrace();
         if (this.getChinesses(e.getMessage())!=null){
            return ResponseUtil.fail(-1,"中台调用出错_pms2CenterUpdateStatus ___<修改渠道状态>___" + this.getChinesses(e.getMessage()));
         }
         return ResponseUtil.fail(-1,"中台调用出错_pms2CenterUpdateStatus ___<修改渠道状态>___"+e.getMessage());
      }
      if (!voidRestResponse.getResultCode().equals("0")) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         logger.error(" ------- 中台执行失败_pms2CenterUpdateStatus ___< 修改渠道状态  >--------" + voidRestResponse.getResultMsg());
         return ResponseUtil.fail(-1,voidRestResponse.getResultMsg());
      }
      return null;
   }


   @Override
   public PartnerVO getByUser(UserVO user) {
      //根据当前user所属
      return partnerService.getByUserCode(user.getUserCode());
   }

   @Override
   public PartnerVO getCasById(String partnerId) {
      return partnerService.getCasById(partnerId);
   }

   @Override
   public List listSel(PartnerVO v) {

      if(StringUtils.isNotEmpty(v.getBusinessCodeIn())){
         String[] codes = v.getBusinessCodeIn().split(",");
         String calc = "";
         for(int i=0;i<codes.length;i++){
               calc+= "'"+codes[i]+"'";
            if(i!=codes.length-1){
               calc+= ",";
            }
         }
         v.setBusinessCodeIn(calc);
      }
      return partnerService.listSel(v);
   }
}
